import { defineStore } from 'pinia'
import { filterAsyncRoutes } from '@/utils/router'
import cache from '@/utils/cache'
import type { RouteRecordRaw } from 'vue-router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { wsManager } from '@/utils/websocket'
import { login, getUserInfo } from '@/api/user';
import { TOKEN_KEY } from '@/utils/enums/cacheEnums';
interface LoginResponse {
    code: number
    data: {
        token: string
    }
    message: string
}

export interface UserState {
    token: string
    userInfo: Record<string, any>
    routes: RouteRecordRaw[]
    perms: string[]
}

export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        token: getToken() || '',
        userInfo: {},
        routes: [],
        perms: [],
    }),
    actions: {


        // 登录
        login(params: Record<string, any>) {
            const { username, password } = params
            return new Promise((resolve, reject) => {
                login({ username: username.trim(), password: password }).then(res => {
                    this.token = res.token
                    cache.set(TOKEN_KEY, res.token)
                    resolve(res)
                }).catch(err => {
                    reject(err)
                })
            })
        },

        // 登出
        async logout() {
            try {
                // 断开 WebSocket 连接
                wsManager.disconnect()

                // 清除 token
                this.token = ''
                removeToken()

                // 清除用户信息
                this.userInfo = {}
                this.routes = []
                this.perms = []

                return true
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 获取用户信息
        getUserInfo() {
            return new Promise((resolve, reject) => {
                getUserInfo()
                    .then((data) => {
                        this.userInfo = data.user
                        this.perms = data.permissions
                        this.routes = filterAsyncRoutes(data.menu)
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        }
    },
    getters: {
        getRoutes(state: UserState) {
            return state.routes
        }
    },
})

export default useUserStore